<?php
define("TOKEN", "phonecollection2015");
define("ASEKEY","kB37WREPLn8hLMqVSwije4JdxRZSWCGeTEkd7MwaxN5");

class Model_Message_Webchat
{

    public function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            echo $echoStr;
            exit;
        }
    }

    //响应消息
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $this->logger("R ".$postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
             
            //消息类型分离
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveOhter($postObj);
                    break;
                case "location":
                	$result = $this->receiveOhter($postObj);
                    //$result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                	$result = $this->receiveOhter($postObj);
                    //$result = $this->receiveVoice($postObj);
                    break;
                case "video":
                	$result = $this->receiveOhter($postObj);
                    //$result = $this->receiveVideo($postObj);
                    break;
                case "link":
                	$result = $this->receiveOhter($postObj);
                    //$result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknown msg type: ".$RX_TYPE;
                    break;
            }
            $this->logger("T ".$result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

    
    private function receiveOther($object){
    	$content = "This Function is currently Under Construction!!";
    	$result = $this->transmitText($object, $content);
    }
    
    
    
    //Event 
    
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $content = "Thanks for Subscribe of Phone Collection / iCollection";
                $content .= (!empty($object->EventKey))?("\n From QR CODE SCAN ".str_replace("qrscene_","",$object->EventKey)):"";
                break;
            case "unsubscribe":
                $content = "Unsubscribe Success";
                break;
            case "SCAN":
                $content =  "Scanning".$object->EventKey;
                break;
            case "CLICK":
                switch ($object->EventKey)
                {
                    case "COMPANY":
                        $content = array();
                        $content[] = array("Title"=>"Phone Collection", "Description"=>"Your One Stop Phone Accessories Shop", "PicUrl"=>"http://www.phonecollection.com.au/shopping/img/phone-collection-1417500736.jpg", "Url" =>"http://www.phonecollection.com.au/shopping/index.php");
                        break;
                    default:
                        $content = "Please Click The Menu".$object->EventKey;
                        break;
                }
                break;
            case "LOCATION":
                $content = "Location ".$object->Latitude.";Location ".$object->Longitude;
                break;
            case "VIEW":
                $content = "LINK".$object->EventKey;
                break;
            case "MASSSENDJOBFINISH":
                $content = "Message ID:".$object->MsgID.". Message Result.".$object->Status;
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        if(is_array($content)){
            if (isset($content[0])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }

        return $result;
    }

    //接收文本消息
    private function receiveText($object)
    {
		$arrShop = unserialize(ARR_SHOP_ACTIVE);	
    	$content = '';
    	$keyword = trim($object->Content);
    	$result = '';
    	$shops = new Model_DbTable_Shoplocation();
        //多客服人工回复模式
        if (strstr($keyword, "Hello") || strstr($keyword, "hi")){
            $result = $this->transmitService($object);
        }
        //Auto reply
        else{
			
        	
        	
        	if(strstr($keyword,"shop")){
        		//Shops 
        		
        		$spList = $shops->listAllActive();
        		$content = array();
        		$content[] = array("Title" => "Replay 4 Charactors Shop Code \n To Check Shop Location,Trading Hours and Contacts","Description" => "","PicUrl" => "http://approd9h4leb60v4olh1v.phonecollection.com.au/webchatimg/shop-logo.jpg","Url" => "");
        		$cot = 0;
        		foreach($spList as $spRow){
					if($cot <7){
        			$strTitle = "[".$spRow['name_shop_location_head']."] To Check ".$spRow['name_of_shop'];
        			$content[] = array(
        						"Title" => $strTitle,
        						"Description" =>"",
        						"PicUrl" =>"",
        						"Url" => ""
        					);
					}
					$cot++;
        		}
        		
        		$result = $this->transmitNews($object, $content);
        	}
        	elseif(in_array(strtoupper($keyword),$arrShop,1)){
        		
        		$shopLine = $shops->getNameByHead(strtoupper($keyword));
        		$content = array();
        		$content[] = array("Title" => $shopLine['name_of_shop'],"Description" => "","PicUrl" => "http://approd9h4leb60v4olh1v.phonecollection.com.au/webchatimg/shop-logo.jpg","Url" => "");
        		$content[] = array("Title" => $shopLine['shop_address'],"Description" => "","PicUrl" => "","Url" => "");
        		$content[] = array("Title" => $shopLine['shop_phone'],"Description" => "","PicUrl" => "","Url" => "");
        		
        		$result = $this->transmitNews($object, $content);
        	} 
           elseif(strstr($keyword,"repair")){
           	
           	$content = "Please input Job ID";
           	
           	$result = $this->transmitText($object, $content);
           }
           elseif(is_numeric($keyword)){
           	
           		$repair = new Model_DbTable_Repairjob();
           		$detail = $repair->getJob($keyword);
           		if($detail){
           			$content = "Hi".$detail['customer_name']." \n";
           			$content .= "You fixed your ".$detail['mobile_brand']." ".$detail['mobile_model']." In Our ".$detail['shop_code']."Shop \n";
           			$content .= "On ".$detail['date_start'];
           			
           		}
           		else{
           			$content = "Can Not Find Job ID";
           		}
           		
           		$result = $this->transmitText($object, $content);
           }
           else{
           	//build picture array 
           	$content = array();
           	$content[] = array("Title" => "Phone Collection / iCollection \n Webchat","Description" => "","PicUrl" => "http://approd9h4leb60v4olh1v.phonecollection.com.au/webchatimg/home-logo.jpg","Url" => "");
           	$content[] = array("Title" => "Reply [SHOP] To Check Shop Location","Description" => "","PicUrl" => "http://approd9h4leb60v4olh1v.phonecollection.com.au/webchatimg/shop-icon.jpg","Url" => "");
           	$content[] = array("Title" => "Reply [REPAIR] To Check Repair Status","Description" => "","PicUrl" => "http://approd9h4leb60v4olh1v.phonecollection.com.au/webchatimg/repair-icon.jpg","Url" => "");
           	$content[] = array("Title" => "Reply [SPECIAL] To Find Current Specials","Description" => "","PicUrl" => "http://approd9h4leb60v4olh1v.phonecollection.com.au/webchatimg/special-icon.jpg","Url" => "");
           	$content[] = array("Title" => "Reply [FB] To Check Our Facebook","Description" => "","PicUrl" => "http://approd9h4leb60v4olh1v.phonecollection.com.au/webchatimg/fb-icon.jpg","Url" => "");
           	
           $result = $this->transmitNews($object, $content);	
           	
           }
         
        
        	
        	
        	
        	
        }

        return $result;
    }

    //接收图片消息
    private function receiveImage($object)
    {
        $content = array("MediaId"=>$object->MediaId);
        $result = $this->transmitImage($object, $content);
        return $result;
    }

    //接收位置消息
    private function receiveLocation($object)
    {
        $content = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //接收语音消息
    private function receiveVoice($object)
    {
        if (isset($object->Recognition) && !empty($object->Recognition)){
            $content = "你刚才说的是：".$object->Recognition;
            $result = $this->transmitText($object, $content);
        }else{
            $content = array("MediaId"=>$object->MediaId);
            $result = $this->transmitVoice($object, $content);
        }

        return $result;
    }

    //接收视频消息
    private function receiveVideo($object)
    {
        $content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
        $result = $this->transmitVideo($object, $content);
        return $result;
    }

    //接收链接消息
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //回复文本消息
    private function transmitText($object, $content)
    {
        $xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    //回复图片消息
    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
    <MediaId><![CDATA[%s]]></MediaId>
</Image>";

        $item_str = sprintf($itemTpl, $imageArray['MediaId']);

        $xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复语音消息
    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
    <MediaId><![CDATA[%s]]></MediaId>
</Voice>";

        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);

        $xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复视频消息
    private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "<Video>
    <MediaId><![CDATA[%s]]></MediaId>
    <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
</Video>";

        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

        $xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复图文消息
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return;
        }
        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

    //回复音乐消息
    private function transmitMusic($object, $musicArray)
    {
        $itemTpl = "<Music>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
    <MusicUrl><![CDATA[%s]]></MusicUrl>
    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复多客服消息
    private function transmitService($object)
    {
        $xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //日志记录
    private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 10000;
            $log_filename = "log.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }
    private function https_request($url, $data = null)
    {
    	$curl = curl_init();
    	curl_setopt($curl, CURLOPT_URL, $url);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    	if (!empty($data)){
    		curl_setopt($curl, CURLOPT_POST, 1);
    		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    	}
    	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    	$output = curl_exec($curl);
    	curl_close($curl);
    	return $output;
    }
}


?>